package com.cambright.mixpaint
{
	import com.cambright.IDispose;
	
	import flash.display.Sprite;
	import flash.events.Event;
		
	public class Canvas extends Sprite implements IDispose
	{
		public function Canvas()
		{
			addEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
			invoke();
		}
		
		protected function invoke():void {}
		
		private function _onAddedToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
			addEventListener(Event.RENDER, _onRender);
			addEventListener(Event.REMOVED_FROM_STAGE, _onRemoveFromStage);
		}
		
		private function _onRemoveFromStage(event:Event):void
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, _onRemoveFromStage);
			removeEventListener(Event.RENDER, _onRender);
			addEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
		}
		
		public function dispose():void
		{
			removeEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
			removeEventListener(Event.REMOVED_FROM_STAGE, _onRemoveFromStage);
			removeEventListener(Event.RENDER, _onRender);
		}
		
		private function _onRender(event:Event):void
		{
			if(isChanged) 
			{ 
				draw();
				finish();
			}
		}
		
		protected function get isChanged():Boolean
		{
			var isChanged:Boolean = false;
			isChanged ||= _sizeChanged;
			return isChanged;
		}
		
		protected function draw():void {}
		
		protected function finish():void
		{
			_sizeChanged = false;
		}
		
		private var _sizeChanged:Boolean = true;
		
		private var _width:int = 100;
		override public function get width():Number
		{
			return _width;
		}
		override public function set width(value:Number):void
		{
			if(value < 0) value = 0;
			else value = int(value);
			if(value == _width) return;
			_width = value;
			_sizeChanged = true;
		}
		
		private var _height:int = 100;
		override public function get height():Number
		{
			return _height;
		}
		override public function set height(value:Number):void
		{
			if(value < 0) value = 0;
			else value = int(value);
			if(value == _height) return;
			_height = value;
			_sizeChanged = true;
		}
	}
}